package com.sky.d_lock_free;

import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

import com.google.common.collect.Lists;

/**
 * 实现了一个基于CAS线程安全的计数器方法safeCount和一个非线程安全的计数器count
 * @Author:hjt
 */
public class CounterDemo {

	private AtomicInteger atomicInteger = new AtomicInteger(0);
	
	private int i = 0;
	
	public static void main(String[] args) {
		final CounterDemo cas = new CounterDemo();
		
		List<Thread> ts = Lists.newArrayList();
		
		long start = System.currentTimeMillis();
		for(int j = 0; j <100;j++){
			Thread t = new Thread(new Runnable() {
				
				@Override
				public void run() {
					for(int i=0;i<10000;i++){
						cas.safeCount();
						cas.count();
					}
					
				}
			});
			ts.add(t);
		}
		
		//启动线程
		for(Thread t : ts){
			t.start();
		}
		
		//等待所有线程执行完成
		for(Thread t : ts){
			try {
				t.join();
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
		
		System.out.println(cas.i);
		System.out.println(cas.atomicInteger.get());
		System.out.println(System.currentTimeMillis() - start);
	}
	
	/**
	 * 使用CAS实现线程安全计数器
	 */
	private void safeCount() {
		for(;;){
			int i = atomicInteger.get();
			boolean suc = atomicInteger.compareAndSet(i, ++ i);
			if(suc){
				break;
			}
		}
	}
	
	/**
	 * 非线程安全计数器
	 */
	private void count() {
		i ++;
	}
}
